﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class FrontEnd_Control_Product_Edit
    Inherits System.Web.UI.UserControl
    Dim level As String = 0
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function "
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            If Not Request.QueryString("Id").ToString.Equals("0") Then
                hidID.Value = Request.QueryString("Id")

                getStore()
                getNghanhHang()
                getMenu()
                ShowData()
            End If
        End If
    End Sub

    Protected Sub getNghanhHang()

        ddlNganhHang.Items.Clear()
        ddlNganhHang.AppendDataBoundItems = True
        ddlNganhHang.Items.Add(New ListItem("---Chọn---", "0"))
        Using data As New VSEntities
            Dim p = (From q In data.Categories Where q.ParentId = 0 Select q.CatId, q.Title).ToList
            ddlNganhHang.DataValueField = "CatId"
            ddlNganhHang.DataTextField = "Title"
            ddlNganhHang.DataSource = p
            ddlNganhHang.DataBind()
            ddlNganhHang.SelectedValue = 0
        End Using

    End Sub
    Protected Sub getMenu(Optional ByVal intMenuID As Integer = 0)
        ddlType.Items.Clear()
        ddlType.AppendDataBoundItems = True
        ddlType.Items.Insert(0, New ListItem("---Chon---", "0"))
        Using data As New VSEntities
            Dim query As List(Of Category)
            'If intStore > 0 Then
            '    Dim p = (From h In data.StoreTypes Where h.StoreID = ddlStore.SelectedValue Select h.RootCateId).Distinct.ToArray
            '    query = (From q In data.Categories Where p.Contains(q.CatId) Order By q.Sort Ascending Select q).ToList
            'Else
            '    Dim p = (From h In data.StoreTypes Select h.RootCateId).Distinct.ToArray
            '    query = (From q In data.Categories Where p.Contains(q.CatId) Order By q.Sort Ascending Select q).ToList
            'End If
            query = (From q In data.Categories Where q.ParentId = intMenuID Order By q.Sort Ascending Select q).ToList

            ddlType.DataValueField = "CatId"
            ddlType.DataTextField = "Title"
            If Not query Is Nothing Then
                For i As Integer = 0 To query.Count - 1
                    ddlType.Items.Add(New ListItem(query.Item(i).Title, query.Item(i).CatId))
                    RecursiveFillTree(query, query.Item(i).CatId)
                Next
            End If
        End Using
    End Sub
    Private Sub RecursiveFillTree(ByVal dtParent As List(Of Category), ByVal parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()

        For j As Integer = 0 To level - 1

            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If

        Using data As New VSEntities
            Dim dv As List(Of Category) = (From q In data.Categories Where q.ParentId = parentID Select q).ToList
            Dim i As Integer
            If dv.Count > 0 Then
                For i = 0 To dv.Count - 1
                    Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).Title.ToString()), dv.Item(i).CatId.ToString())
                    ddlType.Items.Add(itm)
                    RecursiveFillTree(dtParent, Integer.Parse(dv.Item(i).CatId.ToString()))
                Next
            End If
        End Using
        level -= 1
        'on the each function end level will decrement by 1
    End Sub
    Protected Sub getStore()
        ddlStore.Items.Clear()
        ddlStore.AppendDataBoundItems = True
        ddlStore.Items.Add(New ListItem("---Chọn---", "0"))
        Dim intUserID As Integer = Session("UserID")
        Using data As New VSEntities
            Dim p = (From q In data.Stores Where q.UserId = intUserID Select q.StoreId, q.Title).ToList
            ddlStore.DataValueField = "StoreId"
            ddlStore.DataTextField = "Title"
            ddlStore.DataSource = p
            ddlStore.DataBind()
            ddlStore.SelectedValue = 0
        End Using

    End Sub


    Protected Sub ShowData()
        Using data As New VSEntities
            Dim p As Product = (From q In Data.Products Where q.ProductId = hidID.Value Select q).SingleOrDefault
            If Not p Is Nothing Then
                txtTitle.Text = IIf(IsNothing(p.Title) = True, "", p.Title)
                txtDescription.Text = IIf(IsNothing(p.Description) = True, "", p.Description)
                hidImagePath.Text = IIf(IsNothing(p.ImagePreview) = True, "", p.ImagePreview)
                imgUpload.ImageUrl = IIf(IsNothing(p.ImagePreview) = True, "", p.ImagePreview)
                txtOriginalprice.Text = IIf(IsNothing(p.OriginalPrice) = True, "", p.OriginalPrice)
                txtSellprice.Text = IIf(IsNothing(p.SellPrice) = True, "", p.SellPrice)
                ddlStore.SelectedValue = IIf(IsNothing(p.StoreId) = True, 0, p.StoreId)
                chkIsselloff.Checked = IIf(IsNothing(p.IsSellOff) = True, False, p.IsSellOff)
                chkIshot.Checked = IIf(IsNothing(p.IsHot) = True, False, p.IsHot)
                txtTongSo.Text = IIf(IsNothing(p.TongSo), "", p.TongSo.ToString)

                txtDiachi.Text = IIf(IsNothing(p.DiaChi) = True, "", p.DiaChi)
                txtPhone.Text = IIf(IsNothing(p.Phone) = True, "", p.Phone)
                txtPhoneother.Text = IIf(IsNothing(p.PhoneOther) = True, "", p.PhoneOther)
                txtHoten.Text = IIf(IsNothing(p.HoTen) = True, "", p.HoTen)
                txtYahooid.Text = IIf(IsNothing(p.YahooId) = True, "", p.YahooId)
                txtSkypeid.Text = IIf(IsNothing(p.SkypeId) = True, "", p.SkypeId)
                txtWeburl.Text = IIf(IsNothing(p.WebUrl) = True, "", p.WebUrl)

                ddlNganhHang.SelectedValue = IIf(IsNothing(p.Category.ParentId) = True, 0, p.Category.ParentId)
                getMenu(ddlNganhHang.SelectedValue)
                ddlType.SelectedValue = IIf(IsNothing(p.CateID) = True, 0, p.CateID)
                Dim strImage As String = ""
                Dim t = (From a In data.ProductImages Where a.ProductId = p.ProductId Select a.ProductId, a.ImageURL, a.Description).ToList
                If Not t Is Nothing Then
                    For i As Integer = 0 To t.Count - 1
                        strImage += "showImage('" + i.ToString + "','" + t.Item(i).ImageURL.ToString + "','" + t.Item(i).Description.ToString + "');"
                    Next
                End If
                Excute_Javascript(strImage, Me.Page, True)
            End If
        End Using
    End Sub
#End Region
#Region "Event for control"
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim arrImage() As String = hidStrImage.Text.Trim.Split(",")
        Dim arrDest() As String = hidStrCommnet.Text.Trim.Split(";")
        Using data As New VSEntities
            Dim p As Product = (From q In data.Products Where q.ProductId = hidID.Value).SingleOrDefault
            Try
                p.ProductId = hidID.Value
                p.Title = txtTitle.Text.Trim()
                p.QueryString = makeURLFriendly(txtTitle.Text.Trim())
                p.Description = txtDescription.Text.Trim()
                p.ImagePreview = hidImagePath.Text.Trim

                p.OriginalPrice = Math.Round(Decimal.Parse(txtOriginalprice.Text.Trim()), 2)
                p.SellPrice = Math.Round(Decimal.Parse(IIf(String.IsNullOrWhiteSpace(txtSellprice.Text.Trim()) = True, 0, txtSellprice.Text.Trim)), 2)

                If ddlStore.SelectedValue = 0 Then
                    p.StoreId = Nothing
                else
                    p.StoreId = ddlStore.SelectedValue
                End If

                p.Modified = Now
                p.ModifierId = Session("UserID")
                p.IsSellOff = chkIsselloff.Checked
                p.IsHot = chkIshot.Checked
                p.CateID = ddlType.SelectedValue
                p.TinhTrangHang = CInt(ddlStatus.SelectedValue)
                If String.IsNullOrEmpty(txtTongSo.Text.Trim) = True Then
                    p.TongSo = 0
                Else
                    p.TongSo = Integer.Parse(txtTongSo.Text.Trim())
                End If

                p.DiaChi = txtDiachi.Text.Trim()
                p.Phone = txtPhone.Text.Trim()
                p.PhoneOther = txtPhoneother.Text.Trim()
                p.HoTen = txtHoten.Text.Trim()
                p.YahooId = txtYahooid.Text.Trim()
                p.SkypeId = txtSkypeid.Text.Trim()
                p.WebUrl = txtWeburl.Text.Trim()

                data.SaveChanges()
                If p.ProductId > 0 Then
                    Dim t = (From h In data.ProductImages Where h.ProductId = hidID.Value Select h).ToList
                    For Each h As ProductImage In t
                        data.ProductImages.DeleteObject(h)
                    Next
                    For i As Integer = 0 To arrImage.Length - 2
                        Dim b As New ProductImage
                        b.Description = arrDest(i).ToString
                        b.ImageURL = arrImage(i).ToString
                        b.ProductId = p.ProductId
                        data.ProductImages.AddObject(b)
                    Next
                End If
                data.SaveChanges()
                Insert_App_Log("Update Product:" & txtTitle.Text.Trim & "", Function_Name.Product, Audit_Type.Edit, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='" + MainDomain + "quan-ly-san-pham.html';", Me.Page, True)

            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Cập nhật thất bại.');", Me.Page, True)
            End Try
        End Using
    End Sub
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect(MainDomain & "quan-ly-san-pham.html")
    End Sub
    Protected Sub ddlStore_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlStore.SelectedIndexChanged

        getMenu(ddlStore.SelectedValue)

    End Sub

    Protected Sub ddlNganhHang_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlNganhHang.SelectedIndexChanged

        getMenu(ddlNganhHang.SelectedValue)

    End Sub
#End Region
End Class
